package cn.lzx.transaction.inter.impl;

import cn.lzx.transaction.inter.BusinessServiceInter;
import cn.lzx.transaction.inter.CustomerServiceInter;
import cn.lzx.transaction.inter.ProducerServiceInter;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by lizhenxing on 2017/8/31.
 */

/**
 * Created by lzx on 2016/12/9.
 *
 * spring事务回滚机制(此包下的类验证动态代理的JDK代理方式)
 *
 * 1.默认不配置，事务回滚unchecked exception和error，换句话说也就是只回滚RuntimeException和Error的子类和自身
 * 也就是说想回滚必须继承RuntimeException或Error
 *
 * 2.如果配置了回滚异常类型，那么事务回滚该类型以及子类
 */

@Service
public class BusinessServiceInterImpl implements BusinessServiceInter {

    @Autowired
    private CustomerServiceInter customerService;

    @Autowired
    private ProducerServiceInter producerService;


    /**
     * 测试外部类直接调用标注了@Transactional的方法
     *
     * 默认为unchecked Exception or error 及子类回滚,否则需要定义回滚异常
     */
    @Transactional(rollbackFor = Exception.class)
    public void directlyExchange(Long producerId, Long customerId, Long price) throws Exception {
        customerService.buy(customerId, price);
        producerService.outBuy(producerId, price);
    }



    /**
     * 测试外部类间调用标注了@Transactional的方法
     * 此时必须使用代理实例去调用，否则无法触发拦截器作用
     *
     * 默认为unchecked Exception or error 及子类回滚,否则需要定义回滚异常
     */
    public void indirectlyExchange(Long producerId, Long customerId, Long price) throws Exception {
        BusinessServiceInterImpl currentProxy = (BusinessServiceInterImpl) AopContext.currentProxy();
        currentProxy.doExchange(producerId,customerId,price);
    }

    @Transactional(rollbackFor = Exception.class)
    public void doExchange(Long producerId, Long customerId, Long price) throws Exception {
        customerService.buy(customerId, price);
        producerService.outBuy(producerId, price);
    }
}
